package com.medical.admin.sys.realm;

import cn.hutool.core.util.ObjectUtil;
import com.medical.admin.sys.common.dto.AdminDto;
import com.medical.admin.sys.entity.Admin;
import com.medical.admin.sys.service.AdminService;
import com.qf.medical.utils.BeanConvertUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.realm.AuthenticatingRealm;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.util.ByteSource;

import javax.annotation.Resource;


/*
 * @Date : 2024/4/25 14:28
 * @Created by Lang
 * @ProjectName : smart-community-platform
 */
public class AdminRealm extends AuthenticatingRealm {

    @Resource
    private AdminService adminService;

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String adminAccount = (String) token.getPrincipal();
        Admin admin = adminService.getAdminByAccount(adminAccount);
        if (ObjectUtil.isEmpty(admin)) {
            throw new UnknownAccountException("用户名不存在");
        }
        //判断是否被禁用
        if (admin.getMarAdminStatus() != 1) {
            throw new LockedAccountException("账号被锁定,请与管理员联系");
        }

        AdminDto adminDto = BeanConvertUtils.convertTo(admin, AdminDto::new);
        String salt = admin.getSalt();
        ByteSource bytes = ByteSource.Util.bytes(salt);

        return new SimpleAuthenticationInfo(adminDto, admin.getMarAdminPassword(), bytes, adminAccount);
    }
}
